package com.qf.shixi.exception;

import com.alibaba.fastjson.JSONObject;
import com.qf.shixi.result.ResponseCode;
import com.qf.shixi.result.ResponseData;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

@Component
//拦截控制器抛出的所有异常
public class GlobalException implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {

        ResponseData responseData = new ResponseData();
        if(ex instanceof BusinessException){
            BusinessException e = (BusinessException) ex;
            responseData.setCode(e.getCode());
            responseData.setMessage(e.getInfo());
        }else if(ex instanceof SQLException){
            // 返回sql状态码和消息
            responseData.setCode(ResponseCode.SQLEXCEPTION.getCode());
            responseData.setMessage(ResponseCode.SQLEXCEPTION.getMessage());
        }else {
            responseData.setCode(ResponseCode.ERROR.getCode());
            responseData.setMessage(ResponseCode.ERROR.getMessage());
        }
        try {
            String s = JSONObject.toJSONString(responseData);
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().write(s);
            response.getWriter().flush();
            response.getWriter().close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
